#!/usr/bin/python
import os
import thread
import time

IDLE,CONVERTING,FAILED = range(3)

class mpg123:
    def __init__(self):
        self.__progress = 0
        self.__status = IDLE

    def getStatus(self):
        return self.__status

    def getProgress(self):
        return self.__progress

    def getLog(self):
        return self.__log

    def convertList(self,srcdir,mp3list,dstdir):
        if (self.__status!=CONVERTING):
            thread.start_new_thread(self.__listthread,(srcdir,mp3list,dstdir))

    def __listthread(self,srcdir,mp3list,dstdir):
        for entry in mp3list:
            self.__mpg123thread(srcdir+"/"+entry,dstdir + "/" + entry.replace(".mp3",".wav"))

    def convert(self,src,dst):
        if (self.__status!=CONVERTING):
            thread.start_new_thread(self.__lamethread,(src,dst))

    def __mpg123thread(self,src,dst):
        self.__progress = 0
        self.__status = CONVERTING
        self.__log = ""
        stdin,file = os.popen4("mpg123 -w "+dst+" "+src,"r",0)
        line=""
        while True:
            char=file.read(1)
            if char=="": # Programm beendet ?
                break # Schleife beenden
            if char=="\r" or char=="\n": #Falls Zeilenende oder Zeile ueberschreiben
                self.__log += line + "\n" # Log line
                #print line
                #if line.find("%)|")>=0: # Zeile mit % anzeige rausfiltern
                    #a =line.find("(")
                    #b = line.find(")")
                self.__progress = 50
                line = ""
            else:
                line+=char
        retval = file.close()
        self.__progress=100
        time.sleep(0.2)
        self.__progress=0
        if (retval==None): #OK
            self.__status=IDLE
        else: #Fehler
            self.__status=FAILED
